//package wmmd.disc.webmaster;

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.DatabaseConnector;

public class SearchTopic extends HttpServlet {
    
    //----------------------------------------------------------------------------------------
    /**
     * Called by search.jsp - will find all topics containing search terms and display them
     */
    
    
//procWritePost searches the database for each message based on the ID and table name passed in
//from the main doGet function, and then returns each message
    public void procWritePost(HttpServletRequest request, HttpServletResponse response, int numID, String tName)
    throws ServletException, IOException {
        
        //Variables for the database connection
        DatabaseConnector con2 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        //Statement stmt2 = null;
        //ResultSet rs2 = null;
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        
        int i = 0;
        int ds = 0;
        String tablename = tName;
        
        //try {
            //if the Search Phrase field is not empty
            if(request.getParameter("searchphrase")!="" || !(request.getParameter("searchphrase").equals(""))) {
                
                //Set the database connection
                //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                //String db = request.getParameter("db");
                //String database = "jdbc:odbc:" + db;
                //con2 = new DatabaseConnector(DatabaseConnector.getDatabaseType());
                //stmt2 = con2.createStatement();
                
                //Retrieve the message with the given ID
                //TODO: Query
                String SQL = "SELECT ID,TLevel,Name,Date,Subject FROM " + tablename + " WHERE ID = ?";
                String[][] rs2 = con2.selectSQL(SQL,5,new Object[]{numID});

                //rs2 = stmt2.executeQuery("SELECT * FROM " + tablename + " WHERE ID = " + numID);
                //rs2.next();
                //rs2 = con2.selectWhereSQL(tablename, new String[]{"*"}, "ID", numID);
                //rs2 = stmt2.executeQuery("SELECT * FROM " + tablename + " WHERE ID = " + numID);
                //rs2.next();
                
                //Assign the results to variables
                String id_string = rs2[i][0];
                int topic_level = Integer.valueOf(rs2[i][1]).intValue();
                String name_string = rs2[i][2];
                String date_string = rs2[i][3];
                String subject_string = rs2[i][4];
                /*String id_string = rs2.getString("ID");
                int topic_level = Integer.valueOf(rs2.getString("TLevel")).intValue();
                String name_string = rs2.getString("Name");
                String date_string = rs2.getString("Date");
                String subject_string = rs2.getString("Subject");*/
                
                //Grab just the date portion of the date/time string
                ds = date_string.indexOf(" ");
                
                //If the topic is not a main topic, indent the message when its returned.
                if (topic_level > 1) {
                    for(i=1; i < topic_level; i++) {
                        out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                }
                out.print("<A href=\"displaymessage.jsp?RTID=");
                out.println(id_string + "\">" + subject_string + "</A>" + "<BR>");
                
                if (topic_level > 1) {
                    for(i=1; i < topic_level; i++) {
                        out.print("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
                    }
                }
                out.println("Posted by: <B>" + name_string + "</B>");
                out.println("on " + date_string.substring(0, ds) + "<BR>");
            }
        /*} catch (ClassNotFoundException e) {
            out.println("Couldn't load database driver: " + e.getMessage());
        } catch (SQLException e) {
            out.println("SQLException caught: " + e.getMessage());
        } finally {
            try {
                if (con2 != null) {con2.close();}
            } catch (SQLException ignored) {}
        }*/
    }
    
//doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        
        doGet(request, response);
    }
    
//main doGet method that parses the search phrase and returns the search results
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String db = request.getParameter("db");
        String tablename = request.getParameter("tName");
        //int i;
        int j, k = 0;
        String wdPhrase = "";  //single keywords in array arrPhrase
        String wdMessage = ""; //each word of the message from the table
        Vector arrPhrase = new Vector(); //arrays to store parsed keywords
        String[] arrMessage = {}; //array to hold parsed message from table
        String srchPhrase = "";  //phrase user entered
        String sword = "";
        int numID, found;
        
        //Variables for the database connection
        DatabaseConnector con = new DatabaseConnector(DatabaseConnector.getDatabaseType());
        ResultSet rs1 = null;
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        try {
            //grab the search phrase from the QUERY_STRING
            srchPhrase = request.getParameter("searchphrase");
            
            //if the Search Phrase field is not empty
            if(srchPhrase != null && !srchPhrase.equalsIgnoreCase("null") && srchPhrase.length() > 0) {
                //Parse search phrase into array and filter out common words
                srchPhrase = srchPhrase.toLowerCase();
                
                StringTokenizer tokenizer = new StringTokenizer(srchPhrase, " ");
                while (tokenizer.hasMoreTokens()) {
                    String srch_term = tokenizer.nextToken();
                    arrPhrase.addElement(srch_term);
                }
                arrPhrase = filterWords(arrPhrase);
                
                //If the all the terms in the search phrase were filtered out...
                if(arrPhrase.size()==0) {
                    out.println("<BR><B><CENTER>Sorry, We can't search for " + srchPhrase + ".</CENTER></B> ");
                } else {
                    //Otherwise, get all ID numbers, subjects, and messages from the appropriate table
                    String SQL = "SELECT ID, Subject, Message FROM " + tablename + " ORDER BY ResponseID";
                    rs1 = con.selectSQL_RS(SQL);

                    out.print("<B><CENTER>Here are the results of the search for ");
                    out.print(srchPhrase + "</B></CENTER><BR>");
                    j = 0;
                    k = 0;
                    //Remove commas and periods from Subject and Message strings, then concatenate them
                    while(rs1.next()) {
                        numID = Integer.valueOf(rs1.getString("ID")).intValue();
                        String tmpsub = rs1.getString("Subject");
                        String tmpmsg = rs1.getString("Message");
                        tmpsub = tmpsub.replace('.', ' ');
                        tmpsub = tmpsub.replace(',', ' ');
                        tmpsub = tmpsub.toLowerCase();
                        tmpmsg = tmpmsg.replace('.', ' ');
                        tmpmsg = tmpmsg.replace(',', ' ');
                        tmpmsg = tmpmsg.toLowerCase();
                        String tmpstr = " " + tmpsub + " " + tmpmsg + " ";
                        found = 0;  //keeps track of the number of returned messages
                        
                        //If the concatenated Subject/Message string contains any of the search terms,
                        //look up the full message and write it out.
                        if(tmpstr!="") {
                            for(j=0; j<arrPhrase.size(); j++) {
                                if(tmpstr.indexOf(" " + arrPhrase.get(j) + " ") > 0) {
                                    //Increment the message count
                                    found = found + 1;
                                }
                            }
                            if(found > 0) {
                                //numID = Integer.valueOf(rs1.getString("ID")).intValue();
                                //calls procWritePost to write out the message
                                procWritePost(request, response, numID, tablename);
                                //increment the match count
                                k = k + 1;
                            }
                        }
                    }
                    rs1.close();

                    //Depending on the number of matches, return the match count.
                    if(k == 0) {
                        out.println("<BR><B><CENTER>Sorry, there were no matches.</CENTER></B> ");
                    } else if(k == 1) {
                        out.println("<BR><B><CENTER>There was only one match.</CENTER></B> ");
                    } else {
                        out.println("<br><B><CENTER>A total of " + k + " matches were found.</B></CENTER>");
                    }
                }
            }
        } catch (SQLException e) {
            out.println("SQLException caught: " + e.getMessage());
        } finally {
            try {
                if(rs1 != null) rs1.close();
                if(con != null) con.CleanUp();
            } catch (Exception ignored) {}
        }
    }
    
//filterWords filters out common words from the string the user entered
//and returns the edited searchphrase as a Vector
    public Vector filterWords(Vector v) {
        Vector farrPhrase = new Vector();  //holds the terms that make it through the filter
        
        //list of words to filter out
        String[] swords = {"a", "the", "where", "when", "who", "what", "why", "in", "is", "I", "you", "this", "if", "am", "how", "an", "or", "for"};
        int i, j, filt = 0;
        
        //Check each term in the vector
        for (i = 0; i < v.size(); i++) {
            filt = 0;
            for (j = 0; j < swords.length; j++) {
                //if the term matches a word in the filter list, move on to the next term
                if (v.elementAt(i).equals(swords[j].toString())) {
                    filt = 1;
                    break;
                }
            }
            
            //if the term was not in the filter list, add it to the "filtered" Vector
            if (filt == 0) {
                farrPhrase.addElement(v.elementAt(i));
            }
        }
        return farrPhrase;
    }
}
